package com.lanou3g.code0523.dynamic;

import com.lanou3g.code0523.permission.BaseFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@WebFilter(filterName = "RandomFilter", servletNames = "RandomServlet")
public class RandomFilter extends BaseFilter {
    @Override
    public void doFilter(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        //思路
        //当第一次访问资源的时候 根据servlet输出的结果
        //生成一个html的文件
        //之后只要这个html存在,那么久不去访问servlet了
        //而是直接把这个html返回

        //动态页面静态化,其实就是缓存
        //真正会用redis做
        ServletContext app = servletRequest.getServletContext();
        String filepath = app.getRealPath("") + File.separator + "random.html";
        File file = new File(filepath);
        if (!file.exists()) {
            //生成html文件
            MyResponse myResponse
                    = new MyResponse(servletResponse, servletRequest.getServletContext());
            chain.doFilter(servletRequest, myResponse);
            myResponse.writeFile();
        }
        //请求转发
        servletRequest.getRequestDispatcher("/random.html").forward(servletRequest,servletResponse);
    }
}
